#!/bin/awk -f
# Synopsis: mkrtm
# reads M.ldef L*/2nd.erep
# constructs raw transfer matrix registering layers by energies
BEGIN{
  ARGC=1;
  i=0;
  while(getline<"M.ldef"){
      i++;
      e[i]=$2;
      se[$2]=i;
      ARGC++;
      ARGV[ARGC-1]="L"i"/2nd.erep";
  }
  nla=i;
#  printf "checking "i" layers : ";
}
$1 !~ /^ *\#/{
  line=$0;
  sub(/^.+\#/,"",line);
  split(line,a);
  elay=a[2];
  lay=se[elay];
  if(lay<1||lay>nla){print "PROBLEM LAYER "ARGIND" filename "FILENAME};
  if(se[elay]==""){print "fixed layer "ARGIND" : missing E="a[2]" !!!"}else{
    nn[elay]++;
  };
  line=$0;
  sub(/\#.+$/,"",line);
  na=split(line,a);
#  print na,line;
  for(i=1;i<=na;i++){
    gsub(/ +/,"",a[i]);
    if(a[i]!=""){
      pos=a[i];
#    if(pos>maxp){maxp=pos};
      m[ARGIND,lay]=m[ARGIND,lay]" "pos;
#    print ARGIND,lay,m[ARGIND,lay];
    }
  }
}
END{
  ftm="rTM";
  print "raw Tm -> "ftm;
  print nla" # dimension" > ftm;
  for(i=1;i<=nla;i++){
    for(j=1;j<=nla;j++){
      if(m[i,j]==""){ne=0}else{ne=split(m[i,j],a)};
      if(ne>0){print m[i,j]" # "i,j>>ftm}else{print " # "i,j>>ftm};
    }
  }
}
